from functools import wraps
from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required


def admin_required(view_func):
    """管理员权限装饰器"""
    @wraps(view_func)
    @login_required
    def wrapper(request, *args, **kwargs):
        try:
            if not request.user.userprofile.is_admin:
                messages.error(request, '您没有权限访问此页面')
                return redirect('dashboard')
        except AttributeError:
            messages.error(request, '用户信息不完整，请联系管理员')
            return redirect('dashboard')
        
        return view_func(request, *args, **kwargs)
    return wrapper


def college_user_required(view_func):
    """二级学院用户权限装饰器"""
    @wraps(view_func)
    @login_required
    def wrapper(request, *args, **kwargs):
        try:
            if not (request.user.userprofile.is_college_user or request.user.userprofile.is_admin):
                messages.error(request, '您没有权限访问此页面')
                return redirect('dashboard')
        except AttributeError:
            messages.error(request, '用户信息不完整，请联系管理员')
            return redirect('dashboard')
        
        return view_func(request, *args, **kwargs)
    return wrapper


def role_required(allowed_roles):
    """角色权限装饰器"""
    def decorator(view_func):
        @wraps(view_func)
        @login_required
        def wrapper(request, *args, **kwargs):
            try:
                user_role = request.user.userprofile.role
                if user_role not in allowed_roles:
                    messages.error(request, '您没有权限访问此页面')
                    return redirect('dashboard')
            except AttributeError:
                messages.error(request, '用户信息不完整，请联系管理员')
                return redirect('dashboard')
            
            return view_func(request, *args, **kwargs)
        return wrapper
    return decorator